# scripts/update_basic.py
#!/usr/bin/env python3
"""
更新股票基本信息脚本
"""
import os
import sys
from pathlib import Path
import time

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def update_stock_basic():
    """更新股票基本信息"""
    from stock_data_system.main import setup_logging, AppConfig, StockDataService
    import logging

    setup_logging(logging.INFO)
    logger = logging.getLogger(__name__)

    print("=" * 50)
    print("股票基本信息更新脚本")
    print("=" * 50)

    try:
        config = AppConfig()
        service = StockDataService(config.database, config.baostock)

        # 检查数据库连接
        if not service.db_manager.check_connection():
            print("❌ 数据库连接失败！")
            return 1

        print("✅ 数据库连接成功")
        print("正在从Baostock获取股票基本信息...")

        start_time = time.time()
        count = service.update_stock_basic()
        elapsed_time = time.time() - start_time

        if count > 0:
            print(f"✅ 成功更新 {count} 只股票基本信息")
            print(f"⏱️  耗时: {elapsed_time:.2f} 秒")

            # 显示统计信息
            stocks = service.get_stock_list()
            if not stocks.empty:
                market_counts = stocks['market'].value_counts()
                print("\n📊 市场分布:")
                for market, count in market_counts.items():
                    print(f"  {market}: {count} 只股票")
        else:
            print("❌ 更新失败或没有获取到数据")
            return 1

        return 0

    except Exception as e:
        print(f"❌ 更新失败: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(update_stock_basic())